package com.onpositive.compactdata;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.carrotsearch.hppc.IntArrayList;
import com.onpositive.wiki3.db.ITitleMapper;

public class FuzzyStringMap {

	protected IntToIntArrayMap internalMap=new IntToIntArrayMap();
	protected ITitleMapper mm;

	public FuzzyStringMap(ITitleMapper mm) {
		super();
		this.mm = mm;
	}

	public int[] getMatches(String vms) {
		int[] is = internalMap.get(buildFuzzyCode(vms));
		IntArrayList m = new IntArrayList();
		for (int q : is) {
			String title = mm.getTitle(q);
			if (isOk(vms, title)) {
				m.add(q);
			}
		}
		return m.toArray();
	}

	private boolean isOk(String vms, String title) {
		String transform = transform(title);
		String transform2 = transform(vms);
		return transform.endsWith(transform2);
	}

	private int buildFuzzyCode(String vms) {
		return transform(vms).hashCode();
	}

	public void write(DataOutputStream s) throws IOException {
		internalMap.store(s);
	}

	public void read(DataInputStream s) throws IOException {
		internalMap.read(s);
	}

	public static String transform(String catTitle) {
		StringBuilder bld = new StringBuilder();
		for (int a = 0; a < catTitle.length(); a++) {
			char charAt = catTitle.charAt(a);
			if (charAt == ' ' || charAt == '_' || charAt == '-') {
				continue;
			}
			bld.append(Character.toLowerCase(charAt));
		}
		return bld.toString();
	}

	public void put(int intValue, int[] array) {
		internalMap.add(intValue, array);
	}

	
}
